package com.qzq.weibo.adapter;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.qzq.weibo.R;
import com.qzq.weibo.activity.ReplyAndRetweetActivity;
import com.qzq.weibo.entity.Comment;
import com.qzq.weibo.entity.User;
import com.qzq.weibo.utils.Utils;
import com.qzq.weibo.view.CircleImageView;

public class CommentsAdapter extends ArrayAdapter<Comment> {

	private LayoutInflater mInflater;
	private int resourceId;
	private Utils utils;
	private String idstr;

	public CommentsAdapter(Context context, int resource,
			List<Comment> objects, String idstr) {
		super(context, resource, objects);

		this.resourceId = resource;
		this.utils = Utils.getInstance(context);
		this.mInflater = LayoutInflater.from(context);
		this.idstr = idstr;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {

		Comment comment = getItem(position);
		User user = comment.getUser();

		View view = null;
		if (convertView == null) {
			view = mInflater.inflate(resourceId, null);

		} else {
			view = convertView;
		}

		CircleImageView iv_avatar = (CircleImageView) view
				.findViewById(R.id.item_comment_iv_avatar);
		TextView tv_screen_name = (TextView) view
				.findViewById(R.id.item_comment_user_screen_name);
		TextView tv_created_at = (TextView) view
				.findViewById(R.id.item_comment_created_at);
		TextView tv_source = (TextView) view
				.findViewById(R.id.item_comment_tv_source);
		TextView tv_text = (TextView) view.findViewById(R.id.item_comment_text);

		ImageView iv_replyComment = (ImageView) view
				.findViewById(R.id.item_comment_iv_reply);

		/** 异步加载头像 */
		utils.loadBitmap(user.getAvatar_large(), iv_avatar, 40, 40);

		tv_screen_name.setText(user.getScreen_name());
		tv_created_at.setText(utils.setSimpleDateTime(comment.getCreated_at()));
		tv_source.setText(comment.getSource());
		tv_text.setText(comment.getText());

		/** 回复图片的点击事件 */
		iv_replyComment.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onClickReplyComment(position);
			}
		});

		return view;
	}

	private void onClickReplyComment(int position) {

		Intent intent = null;
		intent = new Intent(getContext(), ReplyAndRetweetActivity.class);
		intent.putExtra("idstr", idstr);
		intent.putExtra("actionReponse", "reply_comment");
		intent.putExtra("cid", getItem(position).getIdstr());
		intent.putExtra("replyUserName", getItem(position).getUser()
				.getScreen_name());
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		getContext().startActivity(intent);
	}

}
